package net.wofly.sale.commodity.service.impl;

import net.wofly.common.util.Identities;
import net.wofly.sale.commodity.domain.Commodity;
import net.wofly.sale.commodity.domain.CommodityDetailImg;
import net.wofly.sale.commodity.repository.CommodityDetailImgRepository;
import net.wofly.sale.commodity.service.ICommodityDetailImgService;
import net.wofly.sale.commodity.util.ImgType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service("iCommodityDetailImgService")
@Transactional
public class CommodityDetailImgServiceImpl implements ICommodityDetailImgService {

	@Autowired
	CommodityDetailImgRepository commodityDetailImgRepository;

	@Override
	public CommodityDetailImg save(CommodityDetailImg entity) {
		return commodityDetailImgRepository.save(entity);
	}

	@Override
	public void delete(CommodityDetailImg entity) {
		commodityDetailImgRepository.delete(entity);
	}

	@Override
	public void delete(String key) {
		commodityDetailImgRepository.delete(key);
	}

	@Override
	public CommodityDetailImg findOne(String key) {
		return commodityDetailImgRepository.findOne(key);
	}

	@Override
	public List<CommodityDetailImg> save(List<CommodityDetailImg> entityList) {
		return (List<CommodityDetailImg>) commodityDetailImgRepository.save(entityList);
	}

	@Override
	public List<CommodityDetailImg> findByCommodityIDAndImgType(String brandID, Integer imgType) {
		return commodityDetailImgRepository.findByCommodityIDAndImgType(brandID, imgType);
	}

	@Override
	public List<CommodityDetailImg> findByCommodityID(String commodityID) {
		return commodityDetailImgRepository.findByCommodityID(commodityID);
	}

	@Override
	public Commodity save(Commodity commodity) {
		
		List<CommodityDetailImg> commodityDetailImgs = commodity.getCommodityImgs() ;
		
		if (null!=commodityDetailImgs && !commodityDetailImgs.isEmpty()) {
			
			commodityDetailImgRepository.deleteByCommodityID(commodity.getCommodityID());
			
			for(CommodityDetailImg commodityDetailImg:commodityDetailImgs) {
				commodityDetailImg.setCommodityDetailImgID(Identities.uuid2());
				commodityDetailImg.setCommodityID(commodity.getCommodityID());
				commodityDetailImg.setImgType(ImgType.商品.getValue());
				commodityDetailImg.setModifyDate(commodity.getModifyDate());
			}
			
			commodityDetailImgRepository.save(commodityDetailImgs) ;
		}
		
		return commodity ;
	}

	@Override
	public void deleteByCommodityID(String commodityID) {
		commodityDetailImgRepository.deleteByCommodityID(commodityID);
	}
}
